from sqlalchemy.ext.asyncio import AsyncSession

from module_stock.dao.account_dao import AccountDao
from module_stock.dao.stat_stock_dao import StatStockDao
from module_stock.entity.vo.account_vo import AccountPageQueryModel
from module_stock.entity.vo.stat_stock_vo import StatStockPageQueryModel


class StatStockService:
    """
    股票统计模块服务层
    """

    @classmethod
    async def get_stat_stock_list_services(
            cls, query_db: AsyncSession, query_object: StatStockPageQueryModel, is_page: bool = False
    ):
        """
        获取股票统计列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 股票统计列表信息对象
        """
        stat_stock_list_result = await StatStockDao.get_stat_stock_list(query_db, query_object, is_page)

        return stat_stock_list_result

    @classmethod
    async def get_stat_stock_amount_by_account_tag_services(cls, query_db: AsyncSession):
        """
        根据账号标签统计清仓股票资金总和service

        :param query_db: orm对象
        :return: 按账号标签统计的清仓股票资金总和列表
        """
        # 获取所有账户列表
        account_list = await AccountDao.get_account_list(query_db, AccountPageQueryModel(), is_page=False)
        # 提取所有账户标签
        account_tags = list(set(account['accountTag'] for account in account_list if account.get('accountTag')))

        result = {}
        for account_tag in account_tags:
            # 获取该标签下的所有账户
            accounts_with_tag = [account for account in account_list if account.get('accountTag') == account_tag]
            account_tags_list = [account['accountTag'] for account in accounts_with_tag]
            # 查询该标签下所有清仓股票的资金总和
            amount_sum = await StatStockDao.get_cleared_stock_amount_by_account_tags(query_db, account_tags_list)
            result[account_tag] = float(amount_sum) if amount_sum else 0.0

        return result
